/** @odoo-module **/
import { Dialog } from "@web/core/dialog/dialog";
import {EventBus, Component,onWillDestroy, onMounted, mount, xml, useEnv, App, reactive, useState,useRef } from "@odoo/owl";
import { patch } from "@web/core/utils/patch";
import { ActionDialog } from "@web/webclient/actions/action_dialog";
import { useBus, useService } from "@web/core/utils/hooks";
import { registry } from "@web/core/registry";

export class multi_tab_action_container extends Component {
 
    static template = "multi_tab_action_container";
 
    setup() {
      this.mid=1;
      const state = useState({
          tabs: [],
          activeTabId: null,
          bk: {
            Component: null,
            componentProps: null,
          },
      });
      this.menu=useService("menu")
      this.state = state;
      this.state.nav=this.__owl__.parent.children.__1.component
      
      this.actionServiceDef = registry.category("services").get("action");
 
      this.onActionManagerUpdate = ({ detail: info }) => {
          this.mid++;
         



 

          const a1=this.menu.getCurrentApp();
 

         const title1 = a1?.name|| "New Tab";
          const isBlank = info.Component?.name === "BlankComponent";
          if (isBlank) {
           
            state.bk.Component=info.Component ; //  设置空白组件的状态
            state.bk.componentProps=info.componentProps ;
          //  state.tabs.push({ ...info, title1 ,b:true});
          //  state.activeTabId = info.id; // 激活当前 tab
        
        }
        else  {
                 
            state.bk.Component=null ;
            state.bk.componentProps=null ;
            let id1=1000;
            let id2=1000+Math.floor(Math.random() * 1000);
              // 替换当前激活 tab 的内容
            if (a1) {
                id1=a1.id;
            }
           


          let shouye=false;
          if( info.componentProps.action?.tag=="menu") {
            shouye=true;
          }
          let studio=false;
          if( info.componentProps.action?.tag=="studio") {
            studio=true;
          }
          const sss1=state.tabs.find(tab => (tab.appid ==1000 && tab.id==this.activeTabId));
          if(sss1){
          //  shouye=true;
          
          }
           
          const shouyeweb = state.tabs.find(tab => tab.appid ==1000);

            const currentTab = state.tabs.find(tab => tab.appid == id1);
            if(shouye){ //这里判断是将要显示的是是否是首页
                    if (shouyeweb) {
                        const index = state.tabs.findIndex(tab => tab.appid === 1000);
                        if (index !== -1) {
                            state.tabs.splice(index, 1);
                        }
                     
                    }
                    let ssssye={ ...info,id:this.mid, title:'首页' ,appid:1000}
                    setTimeout(async () => {
                      ssssye.abc111=await this.actionServiceDef.start(this.env);
                    }, 500);
                    state.tabs.unshift( ssssye);
                    state.activeTabId = this.mid; // 激活当前 tab

            }else { //根据getCurrentApp 获取的id 判断将要显示的非首页 但是 如果是studio 则根据需要是否显示在当前页面
                if (currentTab  ) {//如果能找到根据getCurrentApp的页面
                   if    (studio) { //是不是studio
                      
                       const sss2=state.tabs.find(tab => ( tab.id==this.activeTabId));
                       
                        Object.assign(sss2, {
                            ...sss2,
                            Component: info.Component,
                            componentProps: info.componentProps,
                        });

                       

                   }
                   else {
                    currentTab.appid=id1;
                    currentTab.b = false;
                    Object.assign(currentTab, {
                        ...currentTab,
                        Component: info.Component,
                        componentProps: info.componentProps,
                    });
           
                
                    currentTab.title = a1?.name || "New Tab";
                    this.menu.setCurrentMenu(id1);
                    state.activeTabId = currentTab.id; // 激活当前 tab
                    this.gengxinzhuangtai();
                    return;
                   }
                  
                }
                else { //首页或者找不到
                    
                  let ssssye1={ ...info,id:this.mid, title:title1 ,appid:id1}
                  setTimeout(async () => {
                    ssssye1.abc111=this.env.services.action;
                  }, 500);
                    
                    state.tabs.push(ssssye1);
                    state.activeTabId = this.mid; // 激活当前 tab
                }
            }



     
           
            // 保持当前 tab 激活，不切换 id！
         
        }
        this.gengxinzhuangtai();

       
          
      };
       
      this.activateTab = (id) => {
        this.state.activeTabId = id;
        
        const a1=this.state.tabs.find(tab => tab.id === id);
        if (a1.appid==1000) {
          a1.abc111= this.actionServiceDef.start(this.env);

        }
     this.env.services.action=a1.abc111;
        const a2=a1.appid;
        if (a2) {
            this.menu.setCurrentMenu(a2);
        }
        this.gengxinzhuangtai();
 
         
      };
     this.closeTab=(tabId)=> {
        const index = this.state.tabs.findIndex(tab => tab.id === tabId);
        if (index >= 0) {
          this.state.tabs.splice(index, 1); // 删除标签
          // 如果关闭的是当前标签，自动切换到其他标签
          if (this.state.activeTabId === tabId) {
            const nextTab = this.state.tabs[index] || this.state.tabs[index - 1];
            if (nextTab) {
              this.state.activeTabId = nextTab.id;
              const a1=this.state.tabs.find(tab => tab.id === nextTab.id);
              if (a1) {
                const a2=a1.appid;
                if (a2) {
                    this.menu.setCurrentMenu(a2);
                }
              }
             
            } else {
              this.state.activeTabId = null;
            }
          }
        }
        setTimeout(() => {
         // this.gengxinzhuangtai();
        }, 500);
       
      }
      this.env.bus.addEventListener("ACTION_MANAGER:UPDATE", this.onActionManagerUpdate);

      onWillDestroy(() => {
          this.env.bus.removeEventListener("ACTION_MANAGER:UPDATE", this.onActionManagerUpdate);
      });
  }
  
  get tabs() {
      return this.state.tabs;
  }
  gengxinzhuangtai() {
   
     let id1=  this.state.activeTabId;
     const a1=this.state.tabs.find(tab => tab.id === id1);
     const a1111=this.menu.getCurrentApp();
     if(a1111)  {
      this.menu.setCurrentMenu(a1111);
    }
     if (a1) {
   
       if(a1.componentProps.action)  {
        if  (a1.componentProps.action.tag=="menu")  {
            this.state.nav.hm.hasHomeMenu=true;
            a1.title = "首页";
        }
        else {
            this.state.nav.hm.hasHomeMenu=false;
            a1.title = a1111?.name || "New Tab";
        }
 
         
       }
       else {
       
         this.state.nav.hm.hasHomeMenu=false;
         a1.title = a1111?.name || "New Tab";
       }
       document.body.classList.toggle("o_home_menu_background",      this.state.nav.hm.hasHomeMenu)
     
     }
  }
  get activeTabId() {
      
 
      
      return  this.state.activeTabId;
  }


}

multi_tab_action_container.components = {
  ActionDialog
  };
  multi_tab_action_container.props =  {"*":true} 
 